<?php defined('SYSPATH') or die('No direct script access.');

class Model_Services_User extends Model implements Jqgrid_GridListener{
	
	public $user;
	
	public function count($criteria = false){
		return ORM::factory("user")->count_all();
	}
		
	public function getList($criteria = false){
		
		if (!$criteria)	$user_list = ORM::factory("user")->find_all()->as_array();
		else{
			if ($criteria->isSearch){
				$user_list = ORM::factory("user")
								->where($criteria->getSQLField("users"),$criteria->getSQLOper(), $criteria->getSQLSearchString())
								->order_by($criteria->sidx,$criteria->sord)
								->limit($criteria->limit)
								->offset($criteria->calcOffset())
								->find_all()
								->as_array();
						
			}else{
				$user_list = ORM::factory("user")->order_by($criteria->sidx,$criteria->sord)->limit($criteria->limit)->offset($criteria->calcOffset())->find_all()->as_array(); 
			}
		
		} 
	
		$dataset = array();
		foreach ($user_list as $user){
			$dataset[$user->id] = array($user->username, $user->password, $user->email);
		}
		
		return $dataset;
	}

	public function get($id){
		return ORM::factory("user")->find($id);
	}
	
	public function save($id, array $data){
		$user = ($id > 0)? ORM::factory("user",$id) : ORM::factory("user");
		$user->username = $data['username'];
		$user->password = $data['password'];
		$user->email = $data['email'];
    	$user->save();
    	
    	$role = ORM::factory('role', array('name' => 'login'));
		if ($user->has('roles', $role)){
    		;#do nothing
    	}else{
    		$user->add('roles', ORM::factory('role')->where('name', '=', 'login')->find());
    	}
    	
    	
    	return $user->id;
	}
	
	public function delete($id){
		$user = ORM::factory("user",$id);
		$user->delete();
		return $id;
	}
	
	
}